package com.zzzy.server.service;

import com.zzzy.framework.common.constant.TokenNameConstant;
import com.zzzy.framework.dto.LoginUser;
import com.zzzy.common.util.ServletUtils;
import com.zzzy.server.common.cache.LoginUserCache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class TokenService {

    @Resource
    private LoginUserCache loginUserCache;

    public String createToken(LoginUser loginUser) {
        String token = UUID.randomUUID().toString();
        loginUser.setToken(token);
        loginUserCache.putLoginUser(token, loginUser);
        return token;
    }

    public String getToken(HttpServletRequest request) {
        return request.getHeader(TokenNameConstant.TOKEN);
    }

    public String getToken() {
        return ServletUtils.getRequest().getHeader(TokenNameConstant.TOKEN);
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        return loginUserCache.getLoginUser(getToken(request));
    }
}
